<template>
  <div class="login-container">
    <div class="login-form-wrapper glass-container">
      <div class="title-container">
        <h3 class="title">低代码开发平台</h3>
      </div>

      <!-- 选项卡切换 -->
      <el-tabs v-model="activeTab" class="auth-tabs">
        <!-- 登录选项卡 -->
        <el-tab-pane label="登录" name="login">
          <el-form
            ref="loginForm"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            autocomplete="on"
            label-position="left"
          >
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="用户名"
                name="username"
                type="text"
                tabindex="1"
                autocomplete="on"
              >
                <i slot="prefix" class="el-icon-user"></i>
              </el-input>
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.enter.native="handleLogin"
              >
                <i slot="prefix" class="el-icon-lock"></i>
              </el-input>
            </el-form-item>

            <el-form-item prop="captcha">
              <div style="display: flex; gap: 10px;">
                <el-input
                  v-model="loginForm.captcha"
                  placeholder="验证码"
                  name="captcha"
                  tabindex="3"
                  autocomplete="off"
                  style="flex: 1;"
                >
                  <i slot="prefix" class="el-icon-picture"></i>
                </el-input>
                <el-button
                  type="info"
                  @click="refreshCaptcha"
                  style="flex: 0 0 100px; font-size: 12px;"
                >
                  {{ captchaCountdown > 0 ? captchaCountdown + 's' : '刷新验证码' }}
                </el-button>
              </div>
            </el-form-item>

            <div v-if="captchaImage" style="margin-bottom: 15px;">
              <img :src="captchaImage" alt="验证码" style="height: 40px; cursor: pointer;" @click="refreshCaptcha" />
              <span style="font-size: 12px; color: #999;">点击刷新</span>
            </div>

            <el-button
              :loading="loginLoading"
              type="primary"
              style="width:100%;margin-bottom:15px;"
              @click="handleLogin"
              class="glass-button"
            >
              登录
            </el-button>

            <div class="form-links">
              <el-link type="primary" @click="activeTab = 'register'">没有账号？注册</el-link>
              <el-divider direction="vertical"></el-divider>
              <el-link type="primary" @click="activeTab = 'forgot'">找回密码</el-link>
            </div>
          </el-form>
        </el-tab-pane>

        <!-- 注册选项卡 -->
        <el-tab-pane label="注册" name="register">
          <el-form
            ref="registerForm"
            :model="registerForm"
            :rules="registerRules"
            class="login-form"
            autocomplete="off"
            label-position="left"
          >
            <el-form-item prop="username">
              <el-input
                v-model="registerForm.username"
                placeholder="用户名"
                name="username"
                type="text"
                autocomplete="off"
              >
                <i slot="prefix" class="el-icon-user"></i>
              </el-input>
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="密码（至少6位）"
                name="password"
                autocomplete="off"
              >
                <i slot="prefix" class="el-icon-lock"></i>
              </el-input>
            </el-form-item>

            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="确认密码"
                name="confirmPassword"
                autocomplete="off"
              >
                <i slot="prefix" class="el-icon-lock"></i>
              </el-input>
            </el-form-item>

            <el-form-item prop="nickname">
              <el-input
                v-model="registerForm.nickname"
                placeholder="昵称（可选）"
                name="nickname"
                type="text"
                autocomplete="off"
              >
                <i slot="prefix" class="el-icon-user-solid"></i>
              </el-input>
            </el-form-item>

            <el-form-item prop="email">
              <el-input
                v-model="registerForm.email"
                placeholder="邮箱（用于找回密码）"
                name="email"
                type="email"
                autocomplete="off"
              >
                <i slot="prefix" class="el-icon-message"></i>
              </el-input>
            </el-form-item>

            <el-button
              :loading="registerLoading"
              type="primary"
              style="width:100%;margin-bottom:15px;"
              @click="handleRegister"
              class="glass-button"
            >
              注册
            </el-button>

            <div class="form-links">
              <el-link type="primary" @click="activeTab = 'login'">已有账号？登录</el-link>
            </div>
          </el-form>
        </el-tab-pane>

        <!-- 找回密码选项卡 -->
        <el-tab-pane label="找回密码" name="forgot">
          <el-form
            ref="forgotForm"
            :model="forgotForm"
            :rules="forgotRules"
            class="login-form"
            autocomplete="off"
            label-position="left"
          >
            <!-- 第一步：身份验证 -->
            <div v-if="!forgotForm.verified">
              <el-form-item prop="email">
                <el-input
                  v-model="forgotForm.email"
                  placeholder="请输入注册时填写的邮箱"
                  name="email"
                  type="email"
                  autocomplete="off"
                >
                  <i slot="prefix" class="el-icon-message"></i>
                </el-input>
              </el-form-item>

              <el-form-item prop="nickname">
                <el-input
                  v-model="forgotForm.nickname"
                  placeholder="请输入昵称（用于验证身份）"
                  name="nickname"
                  type="text"
                  autocomplete="off"
                >
                  <i slot="prefix" class="el-icon-user-solid"></i>
                </el-input>
              </el-form-item>

              <el-button
                :loading="forgotLoading"
                type="primary"
                style="width:100%;margin-bottom:15px;"
                @click="handleVerifyUser"
                class="glass-button"
              >
                验证身份
              </el-button>
            </div>

            <!-- 第二步：修改密码 -->
            <div v-else>
              <el-alert
                title="身份验证成功！请设置新密码"
                type="success"
                :closable="false"
                style="margin-bottom: 15px;"
              ></el-alert>

              <el-form-item prop="newPassword">
                <el-input
                  v-model="forgotForm.newPassword"
                  type="password"
                  placeholder="新密码（至少6位）"
                  name="newPassword"
                  autocomplete="off"
                >
                  <i slot="prefix" class="el-icon-lock"></i>
                </el-input>
              </el-form-item>

              <el-form-item prop="confirmPassword">
                <el-input
                  v-model="forgotForm.confirmPassword"
                  type="password"
                  placeholder="确认密码"
                  name="confirmPassword"
                  autocomplete="off"
                >
                  <i slot="prefix" class="el-icon-lock"></i>
                </el-input>
              </el-form-item>

              <el-button
                :loading="forgotLoading"
                type="primary"
                style="width:100%;margin-bottom:15px;"
                @click="handleResetPassword"
                class="glass-button"
              >
                重置密码
              </el-button>

              <el-button
                type="default"
                style="width:100%;"
                @click="handleBackToVerify"
                class="glass-button"
              >
                返回重新验证
              </el-button>
            </div>

            <div class="form-links" style="margin-top: 15px;">
              <el-link type="primary" @click="activeTab = 'login'">返回登录</el-link>
            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { login, register, resetPassword, verifyIdentity } from '@/api/user'

export default {
  name: 'Login',
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.registerForm.confirmPassword !== '') {
          this.$refs.registerForm.validateField('confirmPassword')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    const validatePass3 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.forgotForm.confirmPassword !== '') {
          this.$refs.forgotForm.validateField('confirmPassword')
        }
        callback()
      }
    }
    const validatePass4 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.forgotForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    const validateCaptcha = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码'))
      } else if (value.length !== 4) {
        callback(new Error('验证码长度为4位'))
      } else {
        callback()
      }
    }

    return {
      activeTab: 'login',
      loginForm: {
        username: 'admin',
        password: 'admin123',
        captcha: ''
      },
      loginRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        captcha: [{ required: true, validator: validateCaptcha, trigger: 'blur' }]
      },
      registerForm: {
        username: '',
        password: '',
        confirmPassword: '',
        nickname: '',
        email: ''
      },
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validatePass, trigger: 'blur' },
          { min: 6, message: '密码长度至少 6 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ]
      },
      forgotForm: {
        email: '',
        nickname: '',
        newPassword: '',
        confirmPassword: '',
        verified: false
      },
      forgotRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
        newPassword: [
          { required: true, validator: validatePass3, trigger: 'blur' },
          { min: 6, message: '密码长度至少 6 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validatePass4, trigger: 'blur' }
        ]
      },
      captchaImage: null,
      captchaCountdown: 0,
      captchaKey: '',
      loginLoading: false,
      registerLoading: false,
      forgotLoading: false
    }
  },
  methods: {
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          // 验证验证码
          const savedCaptcha = sessionStorage.getItem('captchaCode')
          if (!savedCaptcha) {
            this.$message.error('请先刷新验证码')
            return
          }
          if (this.loginForm.captcha.toUpperCase() !== savedCaptcha) {
            this.$message.error('验证码错误')
            this.loginForm.captcha = ''
            this.refreshCaptcha()
            return
          }
          
          this.loginLoading = true
          login(this.loginForm)
            .then(res => {
              this.$store.dispatch('user/login', res.data)
              this.$message.success('登录成功')
              sessionStorage.removeItem('captchaCode')
              this.$router.push('/')
            })
            .catch(() => {
              this.loginLoading = false
              this.refreshCaptcha()
            })
        }
      })
    },
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.registerLoading = true
          register({
            username: this.registerForm.username,
            password: this.registerForm.password,
            nickname: this.registerForm.nickname || this.registerForm.username,
            email: this.registerForm.email
          })
            .then(res => {
              this.$message.success('注册成功，请登录')
              this.activeTab = 'login'
              this.loginForm.username = this.registerForm.username
              this.loginForm.password = ''
              this.registerForm = {
                username: '',
                password: '',
                confirmPassword: '',
                nickname: '',
                email: ''
              }
            })
            .catch(() => {
              this.registerLoading = false
            })
            .finally(() => {
              this.registerLoading = false
            })
        }
      })
    },
    handleResetPassword() {
      this.$refs.forgotForm.validate(valid => {
        if (valid) {
          this.forgotLoading = true
          resetPassword({
            email: this.forgotForm.email,
            nickname: this.forgotForm.nickname,
            password: this.forgotForm.newPassword
          })
            .then(res => {
              this.$message.success('密码重置成功，请登录')
              this.activeTab = 'login'
              this.loginForm.username = this.forgotForm.email
              this.loginForm.password = ''
              this.forgotForm = {
                email: '',
                nickname: '',
                newPassword: '',
                confirmPassword: '',
                verified: false
              }
            })
            .catch(() => {
              this.forgotLoading = false
            })
            .finally(() => {
              this.forgotLoading = false
            })
        }
      })
    },
    // 验证用户身份
    handleVerifyUser() {
      if (!this.forgotForm.email || !this.forgotForm.nickname) {
        this.$message.error('请输入邮箱和昵称')
        return
      }
      this.forgotLoading = true
      verifyIdentity({
        email: this.forgotForm.email,
        nickname: this.forgotForm.nickname
      })
        .then(res => {
          this.forgotLoading = false
          this.forgotForm.verified = true
          this.$message.success('身份验证成功，请设置新密码')
        })
        .catch(() => {
          this.forgotLoading = false
        })
    },
    // 返回重新验证
    handleBackToVerify() {
      this.forgotForm.verified = false
      this.forgotForm.newPassword = ''
      this.forgotForm.confirmPassword = ''
    },
    // 刷新验证码
    refreshCaptcha() {
      if (this.captchaCountdown > 0) {
        return
      }
      // 生成验证码
      const captchaCode = this.generateCaptcha()
      this.captchaImage = 'data:image/svg+xml;base64,' + btoa(captchaCode.svg)
      this.captchaKey = captchaCode.key
      
      // 倒计时
      this.captchaCountdown = 60
      const timer = setInterval(() => {
        this.captchaCountdown--
        if (this.captchaCountdown <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    },
    // 生成验证码
    generateCaptcha() {
      const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
      let code = ''
      for (let i = 0; i < 4; i++) {
        code += chars.charAt(Math.floor(Math.random() * chars.length))
      }
      
      // 存储验证码到sessionStorage
      sessionStorage.setItem('captchaCode', code)
      
      // 生成SVG验证码
      const svg = this.generateCaptchaSvg(code)
      return { svg, key: code }
    },
    // 生成SVG验证码图片
    generateCaptchaSvg(code) {
      let svg = `<svg width="100" height="40" xmlns="http://www.w3.org/2000/svg">`
      svg += `<rect width="100" height="40" fill="rgba(30, 30, 60, 0.6)"/>`
      
      // 添加科幻风格干扰线
      for (let i = 0; i < 5; i++) {
        const x1 = Math.random() * 100
        const y1 = Math.random() * 40
        const x2 = Math.random() * 100
        const y2 = Math.random() * 40
        // 霓虹蓝紫色干扰线
        const colors = ['#00c3ff', '#9b14dc', '#00ffea']
        const color = colors[Math.floor(Math.random() * colors.length)]
        svg += `<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="${color}" stroke-width="1" opacity="0.6"/>`
      }
      
      // 添加验证码文字（霓虹效果）
      let x = 15
      for (let i = 0; i < code.length; i++) {
        const rotate = Math.random() * 30 - 15
        // 随机霓虹色
        const colors = ['#00c3ff', '#9b14dc', '#00ffea', '#ff00ff']
        const color = colors[Math.floor(Math.random() * colors.length)]
        svg += `<text x="${x}" y="30" font-size="24" font-weight="bold" 
                      fill="${color}" transform="rotate(${rotate} ${x + 5} 20)"
                      font-family="Arial" text-shadow="0 0 10px ${color}">${code[i]}</text>`
        x += 20
      }
      
      // 添加科幻风格干扰点
      for (let i = 0; i < 30; i++) {
        const x = Math.random() * 100
        const y = Math.random() * 40
        const colors = ['#00c3ff', '#9b14dc', '#00ffea']
        const color = colors[Math.floor(Math.random() * colors.length)]
        svg += `<circle cx="${x}" cy="${y}" r="1" fill="${color}" opacity="0.7"/>`
      }
      
      svg += `</svg>`
      return svg
    }
  },
  mounted() {
    // 页面加载时初始化验证码
    this.refreshCaptcha()
  }
}
</script>

<style scoped lang="scss">
@import '@/assets/styles/global.scss';

.login-container {
  min-height: 100vh;
  width: 100%;
  background-color: $background-light;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.dark .login-container {
  background-color: $background-dark;
}

.login-form-wrapper {
  width: 420px;
  max-width: 90%;
  border-radius: $border-radius-lg;
  padding: 30px;
  position: relative;
  overflow: hidden;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

.dark .login-form-wrapper {
  border: 1px solid rgba(255, 255, 255, 0.05);
}

.login-form {
  width: 100%;
  position: relative;
  z-index: 2;
}

.title-container {
  text-align: center;
  margin-bottom: 30px;
}

.title {
  font-size: 28px;
  color: $text-primary-light;
  margin: 0;
  text-align: center;
  font-weight: bold;
  letter-spacing: 1px;
}

.dark .title {
  color: $text-primary-dark;
}

/* 输入框样式 */
.auth-tabs >>> .el-input__inner {
  background: rgba(255, 255, 255, 0.7);
  border: 1px solid rgba(0, 0, 0, 0.1);
  color: $text-primary-light;
  border-radius: $border-radius-sm;
  transition: $transition-base;
}

.dark .auth-tabs >>> .el-input__inner {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.05);
  color: $text-primary-dark;
}

.auth-tabs >>> .el-input__inner:focus {
  border-color: $primary-color;
  box-shadow: $shadow-small;
}

.dark .auth-tabs >>> .el-input__inner:focus {
  border-color: $dark-primary-color;
  box-shadow: $dark-shadow-small;
}

.auth-tabs >>> .el-input__prefix {
  color: $text-secondary-light;
}

.dark .auth-tabs >>> .el-input__prefix {
  color: $text-secondary-dark;
}

/* 按钮样式 */
.auth-tabs >>> .el-button--primary {
  background: transparent;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: $border-radius-sm;
  color: $text-primary-light;
  font-weight: 500;
  letter-spacing: 1px;
  transition: $transition-fast;
  position: relative;
  overflow: hidden;
}

.dark .auth-tabs >>> .el-button--primary {
  border: 1px solid rgba(255, 255, 255, 0.05);
  color: $text-primary-dark;
}

.auth-tabs >>> .el-button--primary:hover {
  transform: translateY(-1px);
  box-shadow: $shadow-small;
}

.dark .auth-tabs >>> .el-button--primary:hover {
  box-shadow: $dark-shadow-small;
}

.auth-tabs >>> .el-button--primary::after {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: rgba(0, 0, 0, 0.05);
  transform: rotate(30deg);
  transition: all 0.6s ease;
}

.dark .auth-tabs >>> .el-button--primary::after {
  background: rgba(255, 255, 255, 0.05);
}

.auth-tabs >>> .el-button--primary:hover::after {
  transform: rotate(30deg) translate(20%, 20%);
}

/* 选项卡样式 */
.auth-tabs >>> .el-tabs__nav-wrap::after {
  display: none;
}

.auth-tabs >>> .el-tabs__header {
  margin: 0 0 20px 0;
}

.auth-tabs >>> .el-tabs__item {
  color: $text-secondary-light;
  font-weight: 500;
}

.dark .auth-tabs >>> .el-tabs__item {
  color: $text-secondary-dark;
}

.auth-tabs >>> .el-tabs__item.is-active {
  color: $primary-color;
}

.dark .auth-tabs >>> .el-tabs__item.is-active {
  color: $dark-primary-color;
}

.auth-tabs >>> .el-tabs__active-bar {
  background: $primary-color;
}

.dark .auth-tabs >>> .el-tabs__active-bar {
  background: $dark-primary-color;
}

.form-links {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  margin-top: 15px;
}

.form-links >>> .el-divider--vertical {
  margin: 0 8px;
  background-color: rgba(0, 0, 0, 0.1);
}

.dark .form-links >>> .el-divider--vertical {
  background-color: rgba(255, 255, 255, 0.05);
}

.form-links >>> .el-link {
  font-size: 12px;
  color: $primary-color;
}

.dark .form-links >>> .el-link {
  color: $dark-primary-color;
}

.form-links >>> .el-link:hover {
  color: $primary-hover;
  text-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
}

.dark .form-links >>> .el-link:hover {
  color: $dark-primary-hover;
  text-shadow: 0 0 8px rgba(255, 255, 255, 0.1);
}

/* 验证码样式 */
.auth-tabs >>> .el-button--info {
  background: rgba(255, 255, 255, 0.7);
  border: 1px solid rgba(0, 0, 0, 0.1);
  color: $text-primary-light;
  border-radius: $border-radius-sm;
  transition: $transition-base;
}

.dark .auth-tabs >>> .el-button--info {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.05);
  color: $text-primary-dark;
}

.auth-tabs >>> .el-button--info:hover {
  background: rgba(0, 0, 0, 0.05);
  border-color: $primary-color;
  box-shadow: $shadow-small;
}

.dark .auth-tabs >>> .el-button--info:hover {
  background: rgba(255, 255, 255, 0.05);
  border-color: $dark-primary-color;
  box-shadow: $dark-shadow-small;
}
</style>